package com.spence.wsdemo.interceptor;

import com.spence.wsdemo.utils.SocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.*;

import javax.annotation.Resource;

/**
 * @author spence_xu
 * @date 2020/5/21 19:03
 */
@Component
@Slf4j
public class WsEventListener {
    
    @Resource
    private SocketUtils socketUtils;

    @EventListener(SessionSubscribeEvent.class)
    public void subscribe(SessionSubscribeEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        log.error("stomp subscribe : {}", socketUtils.getPrincipal(headerAccessor).getName());
    }

    @EventListener(SessionUnsubscribeEvent.class)
    public void unsubscribe(SessionUnsubscribeEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        log.error("stomp unsubscribe : {}", socketUtils.getPrincipal(headerAccessor).getName());
    }

    @EventListener(SessionDisconnectEvent.class)
    public void disconnect(SessionDisconnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        log.error("stomp disconnect : {}", socketUtils.getPrincipal(headerAccessor).getName());
    }

    @EventListener(SessionConnectEvent.class)
    public void collect(SessionConnectEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        log.error("stomp connect : {}", socketUtils.getPrincipal(headerAccessor).getName());
    }

    @EventListener(SessionConnectedEvent.class)
    public void collected(SessionConnectedEvent event) {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
        log.error("stomp connected : {}", socketUtils.getPrincipal(headerAccessor).getName());
    }
}
